//
//  CZGroupChatVC.m
//  CZWeiXin
//
//  Created by Alvechen on 16/4/13.
//  Copyright © 2016年 alvechen. All rights reserved.
//

#import "CZGroupChatVC.h"
#import "CZChatImgView.h"
#import "CZXMPPRoomManager.h"

@interface CZGroupChatVC ()<UITableViewDataSource,UITableViewDelegate,XMPPStreamDelegate,UITextFieldDelegate,XMPPIncomingFileTransferDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,XMPPOutgoingFileTransferDelegate,XMPPvCardAvatarDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *messageTF;

///聊天记录查询结果控制器
@property (nonatomic,strong) NSFetchedResultsController  *fetchedResultsController;
///保存房间成员  key:假jid字符串  value:真实jid对象
@property (nonatomic,strong) NSMutableDictionary  *occupants;

@end

@implementation CZGroupChatVC

- (NSMutableDictionary *)occupants{
    
    if (_occupants != nil) {
        return _occupants;
    }
    //实例化
    _occupants = [NSMutableDictionary dictionary];
    
    return _occupants;
}

- (NSFetchedResultsController *)fetchedResultsController{
    
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    //实例化
    
    //存储器
     XMPPRoomCoreDataStorage *storage = [XMPPRoomCoreDataStorage sharedInstance];
    
    //查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"XMPPRoomMessageCoreDataStorageObject"];
    //条件(谓词)
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"roomJIDStr == %@",self.jid.bare];
    
    //排序描述器
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"localTimestamp" ascending:YES];
    request.sortDescriptors = @[sortDesc];
    request.predicate = predicate;
    
    //创建查询结果控制器
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:storage.mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    //执行查询
    NSError *error = nil;
    [_fetchedResultsController performFetch:&error];
    
    for (XMPPRoomMessageCoreDataStorageObject *aMessage in _fetchedResultsController.fetchedObjects) {
        
        
        //打印聊天信息
        NSLog(@"发言者:%@-%@",aMessage.jid,aMessage.body);
    }
    
    return _fetchedResultsController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取群成员
    [self fetchOccupants];
    
    //标题
    self.title = self.jid.bare;
    
    
    //流代理
    [[CZXMPPManager shareInstance].xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //文件接收代理
    [[CZXMPPManager shareInstance].xmppIncomingFileTransfer addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //文件发送代理
    [[CZXMPPManager shareInstance].xmppOutgoingFileTransfer addDelegate:self delegateQueue:dispatch_get_main_queue()];
    //成为个人资料头像模块代理
    [[CZXMPPManager shareInstance].xmppvCardAvatarModule addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    
    //获取数据
    [self fetchData];
}

#pragma mark - funcs

- (void)fetchData{
    
    //隔一段时间再去取,让数据库保存好了,才能取到最新数据
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //重新获取数据
        [self.fetchedResultsController performFetch:nil];
        //刷新表格
        [self.tableView reloadData];
        
        //滚动
        NSInteger rowCount = self.fetchedResultsController.fetchedObjects.count;
        
        if (rowCount) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rowCount - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
        
        
        
    });
    
    
}

/**
 * 获取聊天室里的成员
 */
- (void)fetchOccupants{

    //存储器
    XMPPRoomCoreDataStorage *storage = [XMPPRoomCoreDataStorage sharedInstance];
    
    //查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"XMPPRoomOccupantCoreDataStorageObject"];
//    //条件(谓词)
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"roomJIDStr CONTAINS %@",@"@itcasts.im.itcast.cn"];
    
    //排序描述器
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"realJIDStr" ascending:YES];
    request.sortDescriptors = @[sortDesc];
    request.predicate = predicate;
    
    //创建查询结果控制器
    NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:storage.mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    //执行查询
    NSError *error = nil;
    [fetchedResultsController performFetch:&error];
    
    for (XMPPRoomOccupantCoreDataStorageObject *aOccupant in fetchedResultsController.fetchedObjects) {
        
        
        //打印聊天信息
        NSLog(@"假:%@ 真:%@",aOccupant.jidStr,aOccupant.realJIDStr);
        
        //保存到字典  key:假jid字符串(NSString)  value:真实jid对象(XMPPJID)
        
        self.occupants[aOccupant.jidStr] = aOccupant.realJID;
        
        
    }

    
}




#pragma mark - UI事件

/**
 * 选择图片
 */
- (IBAction)sendPicClick:(id)sender {
    
    //图片选取
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //设置代理
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}


#pragma mark - tableView数据源和代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.fetchedResultsController.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //取出数据
    XMPPRoomMessageCoreDataStorageObject *aMessage = self.fetchedResultsController.fetchedObjects[indexPath.row];
    
    //cell类型
    NSString *identifier = aMessage.isFromMe? @"cell_outgoing" : @"cell_incomming";
    
    //判断是否是图片
    if ([aMessage.message.subject isEqualToString:@"IMAGE"]) {
        
        identifier = aMessage.isFromMe? @"cell_outgoing_img" : @"cell_incomming_img";
        
    }
    
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    //赋值
    //头像
    UIImageView *avatarImgV = [cell viewWithTag:100];
    
    //使用个人资料头像模块获得头像
    NSData *avatarData = nil;
    
    //对方jid: self.jid
    //自己jid:xmppStream.myJID
    
    if (aMessage.isFromMe) {
        //我的头像
        avatarData = [[CZXMPPManager shareInstance].xmppvCardAvatarModule photoDataForJID:kCZ_myJID];
    }else{
        
        //取出消息所属成员的真实JID
        XMPPJID *realJID = self.occupants[aMessage.jidStr];
        
        avatarData = [[CZXMPPManager shareInstance].xmppvCardAvatarModule photoDataForJID:realJID];
    }
    
    //是否有头像
    if (avatarData) {
        avatarImgV.image = [UIImage imageWithData:avatarData];
    }else{
        
        //默认头像
        avatarImgV.image = [UIImage imageNamed:@"DefaultHead"];
        
    }
    
    
    //账户名
    UILabel *bodyLb = [cell viewWithTag:101];
    
    //判断是否是图片
    if ([aMessage.message.subject isEqualToString:@"IMAGE"]) {
        
        bodyLb.text = @"这是图片";
        
        //获取图片路径
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        
        //拼接全路径
        NSString *filePath = [path stringByAppendingPathComponent:aMessage.body];
        
        
        //取出气泡视图
        CZChatImgView *imgView = [cell viewWithTag:102];
        
        [imgView setImage:[UIImage imageWithContentsOfFile:filePath] isOutgoing:aMessage.isFromMe];
        
        
        
    }else{
        
        bodyLb.text = aMessage.body;
    }
    
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //取出数据
    XMPPRoomMessageCoreDataStorageObject *aMessage = self.fetchedResultsController.fetchedObjects[indexPath.row];
    //是图片消息cell高度120
    if ([aMessage.message.subject isEqualToString:@"IMAGE"]) {
        
        return 120;
    }
    
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //取出数据
    XMPPRoomMessageCoreDataStorageObject *aMessage = self.fetchedResultsController.fetchedObjects[indexPath.row];
    //是图片消息cell高度120
    if ([aMessage.message.subject isEqualToString:@"IMAGE"]) {
        
        return 120;
    }
    
    return UITableViewAutomaticDimension;
}

#pragma mark - UITextFieldDelegate

/**
 * 按回车时调用
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    //发送消息 Type:类型-chat/groupchat
    XMPPMessage *message = [XMPPMessage messageWithType:@"groupchat" to:self.jid];
    
    //添加消息body
    [message addBody:textField.text];
    
    //使用流发送消息元素
    [[CZXMPPManager shareInstance].xmppStream sendElement:message];
    
    
    
    //清空
    textField.text = @"";
    
    //刷新数据
    [self fetchData];
    
    return YES;
}

#pragma mark - 图片选取代理

/**
 * 图片选取完成
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSLog(@"%@",info);
    
    UIImage *img = info[UIImagePickerControllerOriginalImage];
    
    //图片转成二进制
    NSData *imgData = UIImageJPEGRepresentation(img, 0.1);
    
    //唯一的名字
    NSString *name = [[CZXMPPManager shareInstance].xmppStream generateUUID];
    
    //写入沙盒
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    //拼接全路径
    NSString *filePath = [path stringByAppendingPathComponent:name];
    
    NSLog(@"%@",filePath);
    
    //写入
    [imgData writeToFile:filePath atomically:YES];
    
    
    
    //发送文件  data:要发送的文件  name:指定文件名 toRecipient:接收者jid description:附加信息
    //接收者JID必须包含resource,否则出现错误
    NSError *error = nil;
    [[CZXMPPManager shareInstance].xmppOutgoingFileTransfer sendData:imgData named:name toRecipient:self.jid description:nil error:&error];
    
    if (error) {
        NSLog(@"发送文件error = %@",error);
    }
    
    //打包消息 type:chat-单聊 ,groupchat-群聊
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.jid];
    [message addBody:name];//%file%
    
    //添加subject,用于识别图片
    [message addSubject:@"IMAGE"];
    
    [[XMPPMessageArchivingCoreDataStorage sharedInstance] archiveMessage:message outgoing:YES xmppStream:[CZXMPPManager shareInstance].xmppStream];
    
    //刷新界面
    [self fetchData];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - XMPPStreamDelegate

/**
 * 收到消息的时候调用
 */
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
    
    //从新获取数据刷新表格
    [self fetchData];
    
}

/**
 * 消息发送成功
 */
- (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message{
    
    
}

/**
 * 消息发送失败
 */
- (void)xmppStream:(XMPPStream *)sender didFailToSendMessage:(XMPPMessage *)message error:(NSError *)error{
    
    
    
}

#pragma mark - XMPPIncomingFileTransferDelegate

- (void)xmppIncomingFileTransfer:(XMPPIncomingFileTransfer *)sender didSucceedWithData:(NSData *)data named:(NSString *)name{
    
    //刷新
    [self fetchData];
}

#pragma mark - XMPPOutgoingFileTransferDelegate

- (void)xmppOutgoingFileTransferDidSucceed:(XMPPOutgoingFileTransfer *)sender{
    
}

- (void)xmppOutgoingFileTransfer:(XMPPOutgoingFileTransfer *)sender didFailWithError:(NSError *)error{
    
    NSLog(@"%@",error);
}

#pragma mark - XMPPvCardAvatarDelegate
/**
 * 收到头像更新
 */
- (void)xmppvCardAvatarModule:(XMPPvCardAvatarModule *)vCardTempModule didReceivePhoto:(UIImage *)photo forJID:(XMPPJID *)jid{
    
    //刷新数据
    [self fetchData];
    
}


@end
